import React from 'react'
import { Form, Input, Button, Checkbox } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { connect } from 'react-redux'
import { loginAsync } from '../../actions/user'
import './login.less'
import { Redirect } from 'react-router-dom'

function Login(props) {
  // 表单验证成功，触发提交表单的 onFinish 事件
  const onFinish = (values) => {
    console.log('Received values of form: ', values)
    props.login(values)
  }

  return (
    props.token // 判断，在属性中是否存在用户登录成功的token数据，如果存在，则跳转到管理主页面中
    ?
    <Redirect to="/admin" />
    :
    <Form
      name="normal_login"
      className="login-form"
      initialValues={{
        username: 'admin',
        password: 'admin',
        remember: true,
      }}
      onFinish={onFinish}
      style={{margin: 'auto'}}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: '请输入用户名！',
          },
        ]}
      >
        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: '请输入密码',
          },
        ]}
      >
        <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="请输入密码"
        />
      </Form.Item>
      <Form.Item>
        <Form.Item name="remember" valuePropName="checked" noStyle>
          <Checkbox>记住用户</Checkbox>
        </Form.Item>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" className="login-form-button">
          登录
        </Button>
      </Form.Item>
    </Form>
  )
}

// 将当前组件连接到 redux 的 store
export default connect(state => ({
  token: state.user.token
}), {
  login: loginAsync
})(Login)
